'use strict'
exports.admin = (req, res)=> {
	req.db.driver.execQuery('select uid, utitle from article',(err,list)=>{
		//1.0 判断数据是否报错
		if(err)
		{
			res.end();
			return;
		}
		//2.0 将页面渲染以后响应给浏览器
		res.render('admin.html',{array:list},(err,html)=>{
			res.end(html);
		});
	});
};

exports.getEdit = (req,res)=>{

	//1.0 获取vid的值
	let vid = req.params.vid;
	//2.0 根据vid找到数据
	req.models.article.get(vid,(err,item)=>{
			if(err)
			{
				res.end();
				return;
			}
		res.end(JSON.stringify({"title":item.utitle,"content":item.ucontent}));
	});
};

exports.add = (req, res)=> {
	//1.0 获取浏览器请求body中的所有值
	let utitle = req.body.title;
	let ucontent = req.body.content;
	//2.0 将值入库
	req.models.article.create({
		utitle: utitle,
		ucontent: ucontent,
		ureads:"0",
		uups:"0",
		udowns:"0"
	}, (err, item)=> {
		if (err) {
			res.end('出错了');
			console.log(err);
			return;
		}
		//3.0 响应浏览器
		res.end(JSON.stringify({"id":item.uid,"msg":"新增成功"}));
	});
};

exports.postEdit = (req, res)=> {
//1.0 获取body中的值
	let utitle = req.body.title;
	let ucontent = req.body.content;
	let uid = req.body.id;

//2.0 查询出需要更新的这条数据
	req.models.article.get(uid, (err, item)=> {
		//3.0 修改值
		item.utitle = utitle;
		item.ucontent = ucontent;
		item.save((error)=> {
			if (error) {
				res.end();
				return;
			}
			res.end("数据更新成功");
		});
	})
};

exports.del = (req, res)=> {
//1.0 获取vid
	let vid = req.params.vid;

//2.0 删除数据
	req.db.driver.execQuery('delete from article where uid=' + vid, (err)=> {
		if (err) {
			res.end("删除失败");
			return;
		}
		res.end("删除成功");
	})
};
